import type { Method } from 'alova'
import router from '@/router'

// Custom error class for API errors
export class ApiError extends Error {
  code: number
  data?: any

  constructor(message: string, code: number, data?: any) {
    super(message)
    this.name = 'ApiError'
    this.code = code
    this.data = data
  }
}

/**
 * 统一处理未授权（401/403）错误
 * @description 显示提示、清除用户状态并跳转到登录页面
 */
function handleUnauthorized() {
  const userStore = useUserStore()
  userStore.logout() // 清除用户信息
  const globalToast = useGlobalToast()
  globalToast.error({ msg: '登录已过期，请重新登录！', duration: 500 })
  const timer = setTimeout(() => {
    clearTimeout(timer)
    router.replaceAll({ name: 'login' })
  }, 500)
}

// Define a type for the expected API response structure
interface ApiResponse {
  code: number
  message?: string
  data?: any
  success?: boolean
  total?: number
  more?: boolean
}

// Handle successful responses
export async function handleAlovaResponse(
  response: UniApp.RequestSuccessCallbackResult | UniApp.UploadFileSuccessCallbackResult | UniApp.DownloadSuccessData,
) {
  const globalToast = useGlobalToast()
  // Extract status code and data from UniApp response
  const { statusCode, data } = response as UniNamespace.RequestSuccessCallbackResult

  // 处理401/403错误
  if (statusCode === 401 || statusCode === 403) {
    handleUnauthorized()
    throw new ApiError('登录已过期，请重新登录！', statusCode, data)
  }

  // Handle HTTP error status codes
  if (statusCode >= 400) {
    globalToast.error(`Request failed with status: ${statusCode}`)
    throw new ApiError(`Request failed with status: ${statusCode}`, statusCode, data)
  }

  // The data is already parsed by UniApp adapter
  const json = data as ApiResponse
  // Log response in development
  if (import.meta.env.MODE === 'development') {
    console.log('[Alova Response]', json)
  }

  if (json.code === -2 || json.code === -3) {
    handleUnauthorized()
    throw new ApiError('登录过期，请重新登录！', 403)
  }

  if (json.code !== 0) {
    globalToast.error(json.message || '请求失败')
    throw new ApiError(json.message || '请求失败', json.code, json.data)
  }

  // Return data for successful responses
  return json?.data || json
}

// Handle request errors
export function handleAlovaError(error: any, method: Method) {
  const globalToast = useGlobalToast()
  // Log error in development
  if (import.meta.env.MODE === 'development') {
    console.error('[Alova Error]', error, method)
  }

  // 处理401/403错误
  if (error instanceof ApiError && (error.code === 401 || error.code === 403)) {
    // 在 handleAlovaResponse 中已经处理过一次，这里可以只重新抛出错误
    // 或者根据需要决定是否再次调用 handleUnauthorized
    // 为确保逻辑统一，再次调用
    handleUnauthorized()
    throw error // 重新抛出，让 useRequest 的 onError 能捕获
  }

  // Handle different types of errors
  if (error.name !== 'AbortError' && !(error instanceof ApiError))
    globalToast.error('网络错误，请检查您的网络连接')

  throw error
}
